package com.k2data.k2app.service;

import com.google.common.collect.Lists;
import com.k2data.k2app.common.ResponseConstant;
import com.k2data.k2app.constant.Constant;
import com.k2data.k2app.domain.InstanceClient;
import com.k2data.k2app.domain.SysUser;
import com.k2data.k2app.domain.SysUserPermission;
import com.k2data.k2app.domain.vo.Customer;
import com.k2data.k2app.exception.K2ResponseException;
import com.k2data.k2app.mapper.SysUserMapper;
import com.k2data.k2app.mapper.SysUserPermissionMapper;
import com.k2data.k2app.mapper.SysUserRoleMapper;
import com.k2data.k2app.utils.StringUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author lidong 17-3-6.
 */
@Log4j2
@Service
public class SysUserService {

    private final SysUserMapper sysUserMapper;

    @Autowired
    public SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    public SysUserRoleService sysUserRoleService;
    @Autowired
    private InstanceClient instanceClient;

    @Autowired
    private SysUserPermissionService sysUserPermissionService;

    @Autowired
    public SysUserService(SysUserMapper testMapper) {
        this.sysUserMapper = testMapper;
    }

    @Transactional
    public long insert(SysUser sysUser) throws K2ResponseException {
        //TODO :login user
        sysUser.setCreateBy("");
        sysUser.setUpdateBy("");
        sysUserMapper.insertOfSelective(sysUser);
        if(!StringUtils.isEmpty(sysUser.getRoleId())){
            List<String> roleIds = Lists.newArrayList(sysUser.getRoleId());
            sysUser.setRoleIds(roleIds);
            sysUserRoleService.updateByUser(sysUser);
        }
        sysUserRoleService.updateByUser(sysUser);
        //客户权限关联
        sysUserPermissionService.updateByUser(sysUser);
        return sysUser.getId();
    }

    @Transactional
    public int update(SysUser sysUser) throws K2ResponseException {
        sysUser.setUpdateBy("");
        int num = sysUserMapper.updateByPrimaryKeySelective(sysUser);
        //和角色关联
        if(!StringUtils.isEmpty(sysUser.getRoleId())){
            List<String> roleIds = Lists.newArrayList(sysUser.getRoleId());
            sysUser.setRoleIds(roleIds);
            sysUserRoleService.updateByUser(sysUser);
        }
        //客户权限关联
        sysUserPermissionService.updateByUser(sysUser);
        return num;
    }

    /**
     * 删除用户
     * @param id
     * @return
     * @throws Exception
     */
    @Transactional
    public int deleteById(Long id) throws Exception{
         //1 删除用户
        sysUserMapper.deleteById(id);
        //2 删除和角色关联关系
        sysUserRoleMapper.deleteByUserId(id);
        return 1;
    }


    public Long confirmPwd(Long id,SysUser sysUser) throws K2ResponseException {
        SysUser sysUser1 = sysUserMapper.get(id);
        if(sysUser.getPassword().equals(sysUser1.getPassword())){
            return id;
        } else {
            throw new K2ResponseException(ResponseConstant.PWD_ERROR,
                    String.format("%s(id: %s)", ResponseConstant.PWD_ERROR_STR, id));
        }
    }

    public SysUser get(Long id){
        SysUser sysUser = sysUserMapper.get(id);
        if(sysUser == null){
            return sysUser;
        }
        if(sysUser.getRoleIds()!=null && sysUser.getRoleIds().size()>0){
            sysUser.setRoleId(sysUser.getRoleIds().get(0));
        }
        if(sysUser != null){
            if (!StringUtils.isBlank(sysUser.getPhoto())) {
                sysUser.setPhoto(instanceClient.getGatewayUrl() + Paths.get("/static/", sysUser.getPhoto()).toString());
            } else {
                sysUser.setPhoto("");
            }
            // 用户的客户和权限
            setPermission(sysUser);
        }
        return sysUser;
    }

    public List<SysUser> list (SysUser sysUser){
        List<SysUser> sysUserList = sysUserMapper.selectUsers(sysUser);
        if (sysUserList.size() == 0) { return sysUserList; }
        sysUserList.stream().forEach(item -> {
            if (!StringUtils.isBlank(item.getPhoto())) {
                item.setPhoto(instanceClient.getGatewayUrl() + Paths.get("/static/", item.getPhoto()).toString());
            } else {
                item.setPhoto("");
            }
            if(item.getRoleIds()!=null && item.getRoleIds().size()>0){
                item.setRoleId(item.getRoleIds().get(0));
            }
        });
        return sysUserList;
    }

    /**
     * 用户的客户权限
     *
     * @param sysUser
     * @return
     */
    public SysUser setPermission(SysUser sysUser){
        List<SysUserPermission> sysUserPermissions = sysUserPermissionService.selectByUser(sysUser.getId());
        sysUser.setCustomersPermission(sysUserPermissions);
        List<Customer> customers = Lists.newArrayList();
        for(SysUserPermission s:sysUserPermissions){
            Customer customer = new Customer();
            customer.setId(s.getCustomerId());
            List<String> permission = new ArrayList<>();
            permission.add("readPermission");
            if("yes".equals(s.getEditPermission())){
                permission.add("editPermission");
            }
            if("yes".equals(s.getDelPermission())){
                permission.add("delPermission");
            }
            customer.setPermission(permission);
            customers.add(customer);
        }
        sysUser.setCustomers(customers);

        return sysUser;
    }
}
